Ext.require([
    'Ext.grid.*',
    'Ext.data.*',
    'Ext.util.*',    
    'Ext.ModelManager',
    'Ext.tip.QuickTipManager'
]);

Ext.onReady(function(){
	
	urlListMenu = "../menu/admin_menu.php?accion=list";
	menu.getProxy().url = urlListMenu;
	menu.load();
	
	var productsToSell = [[-1,'Total: ',0]];
	
	var numFid = Ext.create('Ext.form.field.Text',{
		renderTo:'clientId',
		xtype: 'textfield',
		fieldLabel: 'Numero de Fidelidad'
	})

	var productList = Ext.create('Ext.form.field.ComboBox',{
		name: 'txtId_producto_recibir',
		store: menu,
		valueField: 'id',
		displayField: 'full',		
		emptyText: 'Selecciona un producto...',
		listConfig: {
			getInnerTpl: function() {
				return '<div> {producto} - {sabor} - {tamano}</div>';
			}
		},
		width:300,
		renderTo:'productList'
		
	});
	
	var store = Ext.create('Ext.data.ArrayStore', {
        fields: [
			{name: 'id',     type: 'int'},
			{name: 'product'},
			{name: 'price',      type: 'float'}
           
        ],
        data: productsToSell
    });
	
	var addButton = Ext.create('Ext.button.Button', {
		renderTo:'addProductButton',
		text:'Agregar a venta',
		listeners: {
			click: {
				fn: function(){
					var index = productList.getValue()-1;
					var selected = menu.getAt(index);
					var id = selected.get('id');
					var name = selected.get('full');
					var price = selected.get('precio')
					
					//var product = [[id,name,price]];
					productsToSell.unshift([id,name,price]);
					//productsToSell = product.concat(productsToSell);
					
					var total = 0;
					for(var cont=0;cont<productsToSell.length-1;cont++){
						if(productsToSell[cont][0]!=-1){
							total += productsToSell[cont][2];
						}
					}					
					productsToSell[productsToSell.length-1][2] = total;
					store.load();
				}
			}
		}
	});
	

	 var grid = Ext.create('Ext.grid.Panel', {
        store: store,
        stateful: true,
        stateId: 'stateGrid',
        columns: [
            {
                text     : 'Product',
                sortable : false,
                dataIndex: 'product',
				sortable : false,
				width:300
            },
            {
                text     : 'Price',
                width    : 75,                
                renderer : 'usMoney',
                dataIndex: 'price',
				sortable : false,
            },
			{
				xtype: 'actioncolumn',
				width: 25,
				items: [{
					icon   : '../shared/icons/fam/delete.gif',  // Use a URL in the icon config
                    tooltip: 'delete',
                    handler: function(grid, rowIndex, colIndex) {
							if(store.getAt(rowIndex).get('id')!=-1){
								productsToSell.splice(rowIndex,1);
								productsToSell[productsToSell.length-1][2] -= store.getAt(rowIndex).get('price');
							}else{
								productsToSell.splice(0,productsToSell.length-1);
								productsToSell[productsToSell.length-1][2] = 0;	
							}							
							store.load();
					
						}
				}]
			}
		],
		height: 350,
        width: 403,        
        renderTo: 'productSell'
	});
	
	var sellButton = Ext.create('Ext.button.Button', {
		renderTo:'sell',
		text:'Confirmar Venta',
		listeners: {
			click: {
				fn: function(){
					var products = "";
					var total;
					
					for(var cont=0;cont<productsToSell.length;cont++){
						if(productsToSell[cont][0]!=-1){
							products+=(productsToSell[cont][0]+",")
						}else{
							total = productsToSell[cont][2]
						}
					}
					products = products.slice(0,products.lastIndexOf(","))
					var numFid_ = numFid.getValue();
					var req = new Ext.data.Connection();
					req.request({
						params: {products:products,total:total,numFid:numFid_},
						scope:this,
						url: 'admin_venta.php?accion=venta',
						success: function (resp) {
							var data;
							data = Ext.decode(resp.responseText);
							
							if(data.success == "true"){
								Ext.Msg.alert('Success', "La venta se ha realizado con exito<br/>Numero de Ticket: "+data.numTicket);
							}else{
								Ext.Msg.alert('Fail', "Hubo un error al realizar la venta.");
							}						
						},
						failure: function () {
							Ext.Msg.alert('Fail', "Hubo un error al realizar la venta. Error de conexion.");							
						}
					})
				}
			}
		}
	})
	

})
